// pages/login/login.js
import request from '../../utils/request'

let startY = 0; // 手指起始的坐标
let moveY = 0; // 手指移动的坐标
let moveDistance = 0; // 手指移动的距离
const appInstance = getApp();

//启动数据库
const DB = wx.cloud.database()
const userDB = DB.collection('user')
const collectDB = DB.collection('collect')
Page({
  data: {
    disabled: true,
    btnstate: "default",
    phone:'',
    password: "",
    backHide: true,
    cursor:'',                        //账户字数
    pswcursor:'0',
    contentHide : false,
    coverTransform:'translateY(0)',   //控制元素的transform属性
    coveTransition:'',
    shangHua:true
  },

   // 登录的回调
   async login(){
    // 1. 收集表单项数据
    let {phone, password} = this.data;
    // 2. 前端验证
    /*
    * 手机号验证：
    *   1. 内容为空
    *   2. 手机号格式不正确
    *   3. 手机号格式正确，验证通过
    * */
    
    if(!phone){
      // 提示用户
      wx.showToast({
        title: '手机号不能为空',
        icon: 'none'
      })
      return;
    }
    // 定义正则表达式
    let phoneReg = /^1(3|4|5|6|7|8|9)\d{9}$/;
    if(!phoneReg.test(phone)){
      wx.showToast({
        title: '手机号格式错误',
        icon: 'none'
      })
      return;
    }
    
    if(!password){
      wx.showToast({
        title: '密码不能为空',
        icon: 'none'
      })
      return;
    }
  
    // 后端验证
    let result = await request('/login/cellphone', {phone, password, isLogin: true})
    if(result.code === 200){ // 登录成功
      // console.log(result)
      wx.showToast({
        title: '登录成功'
      })
      // 将用户的信息存储至本地
      wx.setStorageSync('userInfo', JSON.stringify(result.profile))
      

      //给数据库添加用户
      console.log(result.profile)
      let that = this
      userDB.where({userId:result.profile.userId}).get({
        success(res){
          // console.log("查询成功：",res)
          if(res.data.length === 0){
           
            // console.log(res.data.length)
            console.log("用户不存在")
            userDB.add({
              data:{
                    phone:that.data.phone/1,
                    password:that.data.password,
                    userId:result.profile.userId,           //数据库记录用户id
                    name:result.profile.nickname,
                    userUrl:result.profile.avatarUrl,
                     },
              success(){
                
                collectDB.add({
                  data:{
                    userId:result.profile.userId, 
                    songlists:[],
                    likemusics:[],
                    likemvs:[]
                  },
                  success(res){
                    console.log("添加成功",res)
                  }
                })
               
              }
            })
          }else{
            // console.log(res.data.length)
            console.log("用户存在")
          }
          appInstance.globalData.userId = result.profile.userId;
        }
      })
      

      // console.log(userDB)
      
      // 跳转至个人中心personal页面
      wx.reLaunch({
        url: '/pages/personal/personal'
      })
    }else if(result.code === 400){
      wx.showToast({
        title: '手机号错误',
        icon: 'none'
      })
    }else if(result.code === 502){
      wx.showToast({
        title: '密码错误',
        icon: 'none'
      })
    }else {
      wx.showToast({
        title: '登录失败，请重新登录',
        icon: 'none'
      })
    }
  },

  //手指点击时触发
  handleTouchStart(event){
    startY = event.touches[0].clientY;
  },
  handleTouchMove(event){ 
    moveY = event.touches[0].clientY;
    moveDistance = moveY - startY ;
    this.setData({
      contentHide : true,

     })
   },
  handleTouchEnd(event){
    if(moveDistance < -30){
    // console.log("dayu")
   this.setData({
    shangHua:false,
    coverTransform:'translateY(-250%)',
    coveTransition:'transform 0.4s linear'
   })

    }else{return}
  },
  
  //发现msg
  sendMsg(e){
    wx.showToast({
      title: '手机或密码错误',
      icon: 'none',
      duration: 2000
    })

  },

  //输入账户触发
  accountInput: function (e) {
    // console.log(e)
    var content = e.detail.value;
    // console.log(content);
    if (content != "") {
      this.setData({ disabled: false, btnstate: "primary", phone: content ,cursor:e.detail.cursor});
    }
  },
  
  //输入密码触发
  pwdBlur: function (e) {
    var password = e.detail.value;
    if (password != "") {
      this.setData({ password: password ,pswcursor : e.detail.cursor });
    }
  }
})